package main

import (
	"context"
	"errors"
	"fmt"

	"gitee.com/wu-jin-feng/fgin"
	reflectPb "gitee.com/wu-jin-feng/fgin/demos/fconsul_test/server/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

type DemoServiceServer struct {
	reflectPb.UnimplementedDemoServiceServer
}

func (s *DemoServiceServer) GetScheme(ctx context.Context, req *reflectPb.GetSchemeReq) (*reflectPb.GetSchemeResp, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	// a := 0
	// _ = 1 / a
	fmt.Println("md is", md)
	if req.Info == nil {
		return nil, errors.New("info 不能为空")
	}
	endData := &reflectPb.GetSchemeResp{
		Data: req.Path + ",gogogo",
		Info: &reflectPb.GetSchemeRespInfo{
			Info: fmt.Sprintf("这是一个info,%s", req.Info.Info),
			Name: fmt.Sprintf("作者是%s", req.Info.Name),
		},
	}
	return endData, nil
}

// 一元拦截器
func fgrpcInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if info.FullMethod == "/grpc.health.v1.Health/Check" {
			// 健康检查忽略日志
			return handler(ctx, req)
		}
		// defer func() {
		// 	if err := recover(); err != nil {
		// 		fmt.Println(err)
		// 	}
		// }()
		fmt.Println("fgrpcInterceptor", info.FullMethod)
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptor end", m, err)
		return m, err
	}
}

func fgrpcInterceptorV1() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if info.FullMethod == "/grpc.health.v1.Health/Check" {
			// 健康检查忽略日志
			return handler(ctx, req)
		}
		fmt.Println("fgrpcInterceptorV1", info.FullMethod)
		// return nil, fmt.Errorf("fgrpcInterceptorV1 异常")
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptorV1 end", m, err)
		return m, err
	}
}

func fgrpcInterceptorV2() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if info.FullMethod == "/grpc.health.v1.Health/Check" {
			// 健康检查忽略日志
			return handler(ctx, req)
		}
		fmt.Println("fgrpcInterceptorV2", info.FullMethod)
		m, err := handler(ctx, req)
		fmt.Println("fgrpcInterceptorV2 end", m, err)
		return m, err
	}
}

// 注册服务端自定义拦截器拦截器
func registeGrpcMidd() {
	opts := []grpc.ServerOption{
		grpc.ChainUnaryInterceptor(
			fgrpcInterceptor(),
			fgrpcInterceptorV1(),
		),
	}
	fgin.RegisterGrpcServerOptions(opts, false, false)
}

func main() {
	// fgin.RegisterGrpcServerOptions([]grpc.ServerOption{}, true, true)
	f := fgin.Fgin{}
	registeGrpcMidd()
	s := f.GetGrpcServer("./test.yaml")
	reflectPb.RegisterDemoServiceServer(s, &DemoServiceServer{})
	f.RunGrpc(s)
}
